<template>
  <div class="chart-container">
    <canvas ref="chartRef" :id="chartId" width="400" height="250"></canvas>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import Chart from 'chart.js/auto'
import type { ChartData, ChartOptions } from 'chart.js'
import { createChartGradient } from '../../api/chart'

interface Props {
  chartId: string
  type: 'line' | 'bar' | 'doughnut'
  data: ChartData
  options?: ChartOptions
  autoResize?: boolean
}

const props = defineProps<Props>()

const chartRef = ref<HTMLCanvasElement>()
let chartInstance: Chart | null = null

// 默认配置
const defaultOptions: ChartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      display: true,
      position: 'top',
      labels: {
        usePointStyle: true,
        padding: 20
      }
    }
  },
  scales: {
    y: {
      beginAtZero: true,
      grid: {
        color: 'rgba(0, 0, 0, 0.05)'
      }
    },
    x: {
      grid: {
        display: false
      }
    }
  }
}

// 初始化图表
const initChart = async () => {
  await nextTick()
  
  const canvas = chartRef.value
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  // 销毁已存在的图表
  if (chartInstance) {
    chartInstance.destroy()
    chartInstance = null
  }
  
  // 合并配置
  const mergedOptions = {
    ...defaultOptions,
    ...props.options
  }
  
  // 为线图创建渐变背景
  if (props.type === 'line' && props.data.datasets) {
    props.data.datasets.forEach((dataset, index) => {
      if (dataset.data && dataset.backgroundColor) {
        // 创建透明版本的颜色作为渐变终点
        const color = dataset.backgroundColor as string
        const transparentColor = color.replace(/[\d.]+\)$/, '0.05)')
        const gradient = createChartGradient(ctx, color, transparentColor)
        dataset.backgroundColor = gradient
      }
    })
  }
  
  chartInstance = new Chart(ctx, {
    type: props.type,
    data: props.data,
    options: mergedOptions
  })
}

// 更新图表数据
const updateChart = () => {
  if (chartInstance) {
    chartInstance.data = props.data
    chartInstance.update()
  } else {
    initChart()
  }
}

// 监听数据变化
watch(() => props.data, updateChart, { deep: true })

// 监听容器大小变化
const handleResize = () => {
  if (chartInstance && props.autoResize) {
    chartInstance.resize()
  }
}

onMounted(() => {
  initChart()
  
  if (props.autoResize) {
    window.addEventListener('resize', handleResize)
  }
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.destroy()
    chartInstance = null
  }
  
  if (props.autoResize) {
    window.removeEventListener('resize', handleResize)
  }
})

// 暴露方法给父组件
defineExpose({
  updateChart,
  resize: handleResize,
  getChart: () => chartInstance
})
</script>

<style scoped>
.chart-container {
  position: relative;
  width: 100%;
  height: 250px;
}
</style>